package com.atguigu.atcrowdfunding.config;
import com.atguigu.atcrowdfunding.service.impl.SecurityUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class AtcrowdFundingSecurityConfig extends WebSecurityConfigurerAdapter  {
//    @Autowired
//    SecurityUserDetailServiceImpl securityUserDetailServiceImpl;

//@Autowired
//AccessDeniedHandler accessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());  //BCryptPasswordEncoder密码编辑器
    }

    /**
     * 1、自定义请求授权访问规则
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/static/**","/welcome.jsp","/toLogin").permitAll()
                .anyRequest().authenticated();//剩下都需要认证

// /login.jsp==POST  用户登陆请求发给Security
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("loginacct")
                .passwordParameter("userpswd")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/main");

        http.csrf().disable();

        http.logout().logoutSuccessUrl("/index");

      //http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
        http.rememberMe();
    }



}
